package com.platform.api;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.platform.annotation.IgnoreAuth;
import com.platform.entity.CategoryEntity;
import com.platform.entity.FootprintEntity;
import com.platform.entity.GoodsEntity;
import com.platform.entity.ProductEntity;
import com.platform.entity.UserEntity;
import com.platform.service.CategoryService;
import com.platform.service.CollectService;
import com.platform.service.FootprintService;
import com.platform.service.GoodsReadPermissionService;
import com.platform.service.GoodsService;
import com.platform.service.GoodsSpecificationService;
import com.platform.service.ProductService;
import com.platform.util.ApiBaseAction;
import com.platform.utils.R;

import io.swagger.annotations.Api;
import jodd.util.StringUtil;

@Api(tags = "API商品相关接口")
@RestController
@RequestMapping("/api/goods")
public class ApiGoodsController extends ApiBaseAction{
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private CategoryService categoryService;
	@Autowired
	private CollectService collectService;
    @Autowired
    private FootprintService footprintService;
    @Autowired
    private GoodsReadPermissionService goodsReadPermissionService;
    @Autowired
    private GoodsSpecificationService goodsSpecificationService;
    @Autowired
    private ProductService productService;

    /**
     * 查看列表
     */
    @IgnoreAuth
    @RequestMapping("/list")
    public R list(
    		@RequestParam Map<String, Object> map) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("isDelete", 0);
        params.put("isOnSale", 1);
        params.put("sidx", "sort_order");
        params.put("order", "desc");
        
        if(map.get("order") != null) {
            params.put("order", map.get("order"));
        }
        if(map.get("brandId") != null) {
            params.put("brandId", map.get("brandId"));
        }
        if(map.get("categoryId") != null) {
            params.put("categoryId", map.get("categoryId"));
        }
        if(map.get("recommendation") != null) {
            params.put("recommendation", map.get("recommendation"));
        }
        
        if(map.get("offset") != null) {
            params.put("offset", Integer.valueOf(map.get("offset").toString()));
        }else {
            params.put("offset", 0);
        }
        if(map.get("limit") != null) {
            params.put("limit", Integer.valueOf(map.get("limit").toString()));
        }else {
            params.put("limit", 6);
        }
        
        List<GoodsEntity> goodsList = goodsService.queryList(params);
        return R.ok().put("goodsList", goodsList);
    }

    /**
     * 查看列表
     */
    @IgnoreAuth
    @RequestMapping("/category/{categoryId}")
    public R category(
    		@PathVariable("categoryId") Integer categoryId,
    		@RequestParam Map<String, Object> map) {
        CategoryEntity category = categoryService.queryObject(categoryId);
        
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("categoryId", categoryId);
        params.put("isDelete", 0);
        params.put("isOnSale", 1);
        params.put("sidx", "sort_order");
        params.put("order", "desc");
        
        if(map.get("order") != null) {
            params.put("order", map.get("order"));
        }
        if(map.get("brandId") != null) {
            params.put("brandId", map.get("brandId"));
        }
        if(map.get("recommendation") != null) {
            params.put("recommendation", map.get("recommendation"));
        }
        
        if(map.get("offset") != null) {
            params.put("offset", Integer.valueOf(map.get("offset").toString()));
        }else {
            params.put("offset", 0);
        }
        if(map.get("limit") != null) {
            params.put("limit", Integer.valueOf(map.get("limit").toString()));
        }else {
            params.put("limit", 6);
        }
        
        List<GoodsEntity> goodsList = goodsService.queryList(params);
        return R.ok().put("goodsList", goodsList).put("category",category);
    }    
    
    /**
     	* 文章、音频、视频等权限类产品查看
     */
    @IgnoreAuth
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id,HttpServletRequest request) {
    	UserEntity currentUser = super.getCurrentUser();
        GoodsEntity goods = goodsService.queryObject(id);
        R result = R.ok();
        if(goods.isPrivilege()) {
            goods = dealPermissionGoods(goods,currentUser);
            result.put("goods", goods);
        }else {	//实物或虚拟物品
        	goods.setUser(currentUser);
            result.put("goods", goods);
            result.put("goodsSpecificationsList", goodsSpecificationService.getGoodsSpecificationsList(id));
            Map<String,Object> params = new HashMap<String,Object>();
            params.put("goodsId", id);
            List<ProductEntity> products = productService.queryList(params, false,currentUser);
            result.put("products", products);
        }
        return result;
    }
    
    private GoodsEntity dealPermissionGoods(GoodsEntity goods,UserEntity currentUser) {
    	if(goods.getUnitPrice().floatValue() <= 0) {
            return goods;
    	}
    	if(currentUser == null) {
    		goods.setBuyed(false);
            return goods;
    	}
    	if(goods.getGoodsType() != 99) {
        	FootprintEntity footprint = new FootprintEntity();
        	footprint.setAddTime(new Date());
        	footprint.setGoodsId(goods.getId());
        	footprint.setUserId(currentUser.getId().longValue());
        	footprintService.save(footprint);
    	}
    	int collectNum = collectService.queryTotalByUserIdGoodsId(currentUser.getId(), goods.getId());
    	goods.setCollect(collectNum);
    	//收费》0
    	logger.info(goods.getUnitPrice().floatValue()  +"==================" + (goods.getUnitPrice().floatValue() > 0));
    	if(goods.getUnitPrice().floatValue() > 0) {
    		Integer[] goodsIds = {goods.getId(),goods.getParentId(),0,3};
        	int hasPermission = goodsReadPermissionService.queryTotalByUserIdGoodsId(goodsIds,currentUser.getId());
        	if(hasPermission > 0) {
                return goods;
        	}else {
            	//是否有转发赠送
            	if(StringUtil.isNotBlank(request.getParameter("from"))) {
                    Integer referenceId = null;
                    if(request.getParameter("referenceId") != null) {
                    	try {
            				referenceId = Integer.valueOf(request.getParameter("referenceId"));
            			} catch (NumberFormatException e) {
            				referenceId = 0;
            			}
                    }
                	int isShareRead = goodsReadPermissionService.isFromSendPermission(goods.getId(),goods.getParentId(),currentUser.getId(),referenceId);
                	if(isShareRead > 0) {
                		//TODO 是否提醒推荐人
                        return goods;
                	}
            	}
            	
        		goods.setBuyed(false);
                return goods;
        	}
    	}
    	return goods;
    }
    
}
